package com.parkcar;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import HttpUtils.HttpHistoryRequest;
import HttpUtils.HttpPayRequest;
import Modle.AliPayBean;
import Modle.OrderDetailBean;
import Modle.ParkItemBean;
import Modle.PayResult;
import util.BaseActivity;
import util.BaseTools;
import util.Constrants;

/**
 * Created by Administrator on 2016/1/15.
 */
public class ParkDetailActivity extends BaseActivity implements View.OnClickListener {
    private String order_no;
    private HttpHistoryRequest parkRequest;
    private OrderDetailBean bean;
    private TextView park_address,in_time,out_time,standard,count_time,count_money,discount_money,userd_money;
    private TextView coupon_money,pay_money,pay_time;
    private TextView amount_tv;
    private ImageView amount_pay,ali_pay,wx_pay;
    private Button pay_bt;
    private int type;
    private HttpPayRequest payRequest;
    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;
    private LinearLayout no_pay_ll,payed_ll;
    private ReChargeListener reChargeListener;
    @Override
    protected void setUpui(Bundle arg0) {
        setContentView(R.layout.activity_park_detail);
        setTitle("停车详情");
        order_no = getIntent().getStringExtra("order_no");
        if(BaseTools.isValueEmpty(order_no)){
            toast("参数丢失");
            finish();
            return;
        }
        initView();
        reChargeListener = new ReChargeListener();
        api = WXAPIFactory.createWXAPI(this, "wxac2843ffa600c3d2", true);
        registerReceiver(reChargeListener, new IntentFilter(Constrants.RECHARG_SUCCESS));
        getData();

    }
    private void initView(){
        park_address = (TextView) findViewById(R.id.park_address);
        in_time = (TextView) findViewById(R.id.in_time);
        out_time = (TextView) findViewById(R.id.out_time);
        standard = (TextView) findViewById(R.id.standard);
        count_time = (TextView) findViewById(R.id.count_time);
        count_money = (TextView) findViewById(R.id.count_money);
        discount_money = (TextView) findViewById(R.id.discount_money);
        userd_money = (TextView) findViewById(R.id.userd_money);
        //待支付控件
        no_pay_ll = (LinearLayout) findViewById(R.id.no_pay_ll);
        amount_tv = (TextView) findViewById(R.id.amount_tv);
        wx_pay = (ImageView) findViewById(R.id.wx_pay);
        ali_pay = (ImageView) findViewById(R.id.ali_pay);
        amount_pay = (ImageView) findViewById(R.id.amount_pay);
        pay_bt = (Button) findViewById(R.id.pay_bt);
        amount_pay.setOnClickListener(this);
        ali_pay.setOnClickListener(this);
        wx_pay.setOnClickListener(this);
        pay_bt.setOnClickListener(this);

        //已支付控件
        payed_ll = (LinearLayout) findViewById(R.id.payed_ll);
        coupon_money = (TextView) findViewById(R.id.coupon_money);
        pay_money = (TextView) findViewById(R.id.pay_money);
        pay_time = (TextView) findViewById(R.id.pay_time);
    }
    @Override
    protected void updateUI(boolean isLogin) {

    }
    private void getData(){
        parkRequest = new HttpHistoryRequest(this,1);
        parkRequest.getOrderDetailById(order_no);
        parkRequest.setmIHttpClinetListener(this);
        parkRequest.doRequest();
    }
    private void addData(){
        park_address.setText(bean.getCar_park().getName());
        in_time.setText("入场时间："+bean.getStart_at());
        out_time.setText("出场时间："+bean.getEnd_at());
        standard.setText("收费标准："+bean.getCar_park().getPrice_desc());
        count_time.setText("停车时长："+BaseTools.getCountTime(bean.getStart_at(),bean.getEnd_at()));
        count_money.setText("停车费用："+bean.getMoney_actual()+"元");
        discount_money.setText("优惠金额："+bean.getMoney_discount()+"元");
        userd_money.setText(bean.getMoney_pay()+"");
        amount_tv.setText("账户余额：65元");
        if(bean.getIs_pay()==0){
            payed_ll.setVisibility(View.GONE);
            no_pay_ll.setVisibility(View.VISIBLE);
        }else {
            payed_ll.setVisibility(View.VISIBLE);
            no_pay_ll.setVisibility(View.GONE);
            pay_time.setText("支付时间：" + bean.getPay_at());
            coupon_money.setText("优惠券抵扣" + bean.getMoney_red_packet() + "元");
            switch (bean.getPayment()) {
                case 1:
                    pay_money.setText("支付宝支付：" + bean.getMoney_pay() + "元");
                    break;
                case 2:
                    pay_money.setText("微信支付：" + bean.getMoney_pay() + "元");
                    break;
                case 3:
                    pay_money.setText("银联支付：" + bean.getMoney_pay() + "元");
                    break;
                case 4:
                    pay_money.setText("账户支付：" + bean.getMoney_pay() + "元");
                    break;
                case 5:
                    pay_money.setText("现金支付：" + bean.getMoney_pay() + "元");
                    break;
            }
        }
    }
    @Override
    public void httpSuccessListener(Bundle successMsg) {
        super.httpSuccessListener(successMsg);
        if(mBaseResult==null){
            toast("与服务器失去连接，请稍后重试");
            return;
        }
        if(parkRequest!=null&&action.equalsIgnoreCase(parkRequest.getAction())){
            if(mBaseResult.getStatus().getRetCode()==0){
                bean = mBaseResult.toObject(OrderDetailBean.class);
                addData();
            }else{
                toast(mBaseResult.getStatus().getMsg());
            }
        }else if(payRequest!=null&&action.equalsIgnoreCase(payRequest.getAction())){
            if(mBaseResult.getStatus().getRetCode()==0){
                    if(type==2){
                        toast("正在调起微信支付");
                        if (!api.isWXAppInstalled()) {
                            toast("未安装微信");
                            return;
                        }
                        if (!api.isWXAppSupportAPI()) {
                            toast("当前版本不支持支付功能");
                            return;
                        }
                        PayReq req = mBaseResult.toObject(PayReq.class);
                        if(req==null){
                            toast("参数丢失，支付失败");
                            return;
                        }
                        if (BaseTools.isValueEmpty(req.packageValue)) {
                            req.packageValue = "Sign=WXPay";
                        }
                        api.sendReq(req);
                    }else if(type==1){
                        AliPayBean bean = mBaseResult.toObject(AliPayBean.class);
                        if (bean!=null) {
                           String order =bean.getParamsStr()+ "&sign=\"" + bean.getSign() + "\"&" + "sign_type=\"RSA\"";
                            alipagy(order);
                        }else{
                            toast("参数丢失，支付失败");
                        }
                    }
            } else {
                    toast(mBaseResult.getStatus().getMsg());
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.amount_pay:
                if(type!=0){
                    amount_pay.setImageResource(R.drawable.selected);
                    ali_pay.setImageResource(R.drawable.select_bg);
                    wx_pay.setImageResource(R.drawable.select_bg);
                    type=0;
                }
                break;
            case R.id.ali_pay:
                if(type!=1){
                    amount_pay.setImageResource(R.drawable.select_bg);
                    ali_pay.setImageResource(R.drawable.selected);
                    wx_pay.setImageResource(R.drawable.select_bg);
                    type=1;
                }
                break;
            case R.id.wx_pay:
                if(type!=2){
                    amount_pay.setImageResource(R.drawable.select_bg);
                    ali_pay.setImageResource(R.drawable.select_bg);
                    wx_pay.setImageResource(R.drawable.selected);
                    type=2;
                }
                break;
            case R.id.pay_bt:
                if(type==0){
                    toast("钱包支付暂未开通");
                    return;
                }
                payRequest = new HttpPayRequest(this,type);
                payRequest.setOrderParam(order_no+"");
                payRequest.setmIHttpClinetListener(this);
                payRequest.doRequest();
                break;
        }
    }
    private void alipagy(final String order_title) {
        {
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    // 构造PayTask 对象
                    PayTask alipay = new PayTask(ParkDetailActivity.this);
                    // 调用支付接口，获取支付结果
                    String result = alipay.pay(order_title, true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    }
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
            @SuppressWarnings("unused")
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SDK_PAY_FLAG: {
                        PayResult payResult = new PayResult((String) msg.obj);
                        /**
                         * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                         * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                         * docType=1) 建议商户依赖异步通知
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
                            toast("支付成功");
                            Intent mIntent = new Intent();
                            mIntent.setAction( Constrants.RECHARG_SUCCESS);
                            sendBroadcast(mIntent);
                        } else {
                            // 判断resultStatus 为非"9000"则代表可能支付失败
                            // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000")) {
                                toast("支付结果确认中");
                            } else {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                toast("支付失败");
                            }
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
        };

    class ReChargeListener extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            getData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(reChargeListener);
    }
}
